$(function() {
  $(document.body).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
    var tab = $(e.target).attr('href'); 
    if (tab == '#myoffers_tab') {
      var reqData = {
        "id": 1,
        "on": "OFFERS",
        "do": "LIST",
        "data": {
          "user_id": user.id
        }
      };
      $.ajax({
        type: "POST",
        url: lib.nodeapi,
        dataType: 'JSON',
        data: {
          msg: $.toJSON(reqData)
        },
        async: false,
        success: function(response) {
           if (response.result) {          
      			try {
      				var template = new EJS({url: '/ejs/myoffers.ejs'});
      				var result = template.render(response);
      			} catch(e) {			
      				return false;
      			}    			    
            $('#myoffers_tab').html(result);                          
           }
        }
      });    
    } else if (tab == '#finance_tab') {
        var params = 'action=user&type=refs';
        $.ajax({
           type: "POST",
           url: "/ansy/ajax.php",
           dataType: 'JSON',
           data: params,
           async: false,
           success: function(response) {
              var json = {'data':eval(response)};
              console.log(json);
        			try {
        				var template = new EJS({url: '/ejs/myrefs.ejs'});
        				var result = template.render(json);
        			} catch(e) {
        				return false;
        			}
              $('#finance_tab .refList').html(result);
           }
        });    
    }
  })

  $(document.body).on("click", "#userSettingsForm .btn-save-portrait-info", function() {
    //$("#userSettingsForm").submit();
  });
  
  $(document.body).on("click", "#userDelete", function() {
    var params = 'action=user&type=delete';
    $.ajax({
       type: "POST",
       url: "/ansy/ajax.php",
       data: params,
       async: false,
       success: function(result){
        alert('Пользователь удален');
        nav.checkAuth();
        location.hash='#search';
       }
    });
  });  
  
  $(document.body).on("submit", "#userSettingsForm", function() {
    lib.flag = $(this).attr('id');
    if ($('[type=submit]', this).hasClass('disabled')) return false;
    $('[type=submit]', this).addClass('disabled');
    var error = [];
    var req = true;
    window.lib.hideErrors();
    $("[req='true']:visible", this).each(function(i) {
      $(this).parent().removeClass('has-error');
      if (!$(this).val().length) {
        $(this).parent().addClass('has-error');
        req = false;
      }
    });
    if (!req) error.push('Заполнены не все обязательные поля.');
    if (error.length) {
      window.lib.showErrors(error, this, true);
      $('[type=submit]', this).removeClass('disabled');
      return false;
    } else {
      var reqData = {
        "id": 1,
        "on": "USER",
        "do": "SET",
        "data": {
          "user": {
            "nick": null,
            "name": $('[name=name]', this).val(),
            "city_id": $('[name=city_id]', this).val(),
            "lang": null,
            "birthday": $('[name=birthday]', this).val(),
            "childs": $('[name=childs]:checked', this).val(),
            "gender": $('[name=gender]:checked', this).val(),
            "foto": $('[name=foto]', this).val(),
            "about": $('[name=about]', this).val(),
            "profession": $('[name=profession]', this).val()
          }
        }
      };
      $.ajax({
        type: "POST",
        url: lib.nodeapi,
        dataType: 'JSON',
        data: {
          msg: $.toJSON(reqData)
        },
        async: false,
        success: function(response) {
          if (response.result == true) {
            window.lib.showSuccess(['Изменения сохранены'], $('#' + lib.flag), true);
            user.name = response.data.user.name;
            user.image = $('#upload_img').attr('src');
            nav.drawRoof();
          } else {
            window.lib.showErrors([response.data.message], $('#' + lib.flag), true);
          }
          $('#'+lib.flag+' [type=submit]').removeClass('disabled');
          return false;
        }
      });
      return false;
    }
  });   
  
  // File Upload  
	$(document.body).on('click', '#userSettingsForm #image_plus', function(){
		$('#upload_input').click();
	});
	
	$(document.body).on('change', '#upload_input', function(){
		var filename = $('#upload_input').val();
		if(filename == '') return;
		
		var fd = new FormData();
		
		if(!fd){
			alert('Browser doesn\'t support window.FormData() object!');
			return;
		}
		
		fd.append('file', document.getElementById('upload_input').files[0]);
		// TODO: append more fields for multiple files download		
		$.ajax({
			type: 'POST',
			url: '/node/file/upload',
			processData: false,
			contentType: false,
			data: fd,
			success: function(data) {
      console.log(data);  				  				
				$('#upload_input').val('');
				var filedata = JSON.parse(data);
				if(filedata.result){
					$('#upload_img').attr('src', '/s3/foto/'+filedata.data.name+'/original.jpg');
					$('#upload_fileid').val(filedata.data.file_id); 
				}
			}
		});
	});
	
	function handleServerResponse(res){
		switch(res.on){
			case 'USER':{
				switch(res['do']){
					case 'GET':{
						if(res.result == true){
							if(res.data.files.name && res.data.files.ext){
								$('#upload_img').attr('src', '/s3/foto/'+res.data.files.name+res.data.files.ext);
							} else {
								$('#upload_img').attr('src', '/css/images/profile.png');
							}
						}
					} break;
				}
			} break;
		}
	}
	///// File Upload     
	

  $(document.body).on("submit", "#offerForm", function() {
    lib.flag = $(this).attr('id');
    if ($('[type=submit]', this).hasClass('disabled')) return false;
    $('[type=submit]', this).addClass('disabled');
    var error = [];
    var req = true;
    window.lib.hideErrors();
    $("[req='true']:visible", this).each(function(i) {
      $(this).parent().removeClass('has-error');
      if (!$(this).val().length) {
        $(this).parent().addClass('has-error');
        req = false;
      }
    });
    if (!req) error.push('Заполнены не все обязательные поля.');
    if (error.length) {
      window.lib.showErrors(error, this, true);
      $('[type=submit]', this).removeClass('disabled');
      return false;
    } else {
      var reqData = {
        "id": 1,
        "on": "OFFERS",
        "do": "ADD",
        "data": {
          "type": "SELL",
          "title": $('[name=title]', this).val(),
          "price": $('[name=price]', this).val(),
          "info": $('[name=info]', this).val(),
          "geo_id": 1
        }
      };
      $.ajax({
        type: "POST",
        url: lib.nodeapi,
        dataType: 'JSON',
        data: {
          msg: $.toJSON(reqData)
        },
        async: false,
        success: function(response) {
          if (response.result == true) {
            var offer_id = response.data.offer_id;
            var time_start,time_end,weekdays;
            if ($('#offerForm [name=timetable]:checked').val()=='always') {
              time_start = '0:00';
              time_end = '23:59';
              weekdays = 'MO,TU,WE,TH,FR,SA,SU';
            } else if ($('#offerForm [name=timetable]:checked').val()=='workingtime') {
              time_start = '9:00';
              time_end = '18:00';
              weekdays = 'MO,TU,WE,TH,FR';            
            } else if ($('#offerForm [name=timetable]:checked').val()=='hollidays') {
              time_start = '9:00';
              time_end = '22:00';
              weekdays = 'SA,SU';            
            }            
            var reqData = {
                "id": 1,
                "on": "SCHEDULE",
                "do": "ADD",
                "data": {
                  "offer_id": offer_id,
                  "time_start": time_start,
                  "time_end": time_end,
                  "weekdays": weekdays
                }
            };
            $.ajax({
              type: "POST",
              url: lib.nodeapi,
              dataType: 'JSON',
              data: {
                msg: $.toJSON(reqData)
              },
              async: false,
              success: function(response) {                
                window.lib.showSuccess(['Предложение создано: offer_id#' + response.data.offer_id], $('#' + lib.flag), true);
                return false;
              }
            });
            return false;
          } else {
            window.lib.showErrors([response.data.message], $('#' + lib.flag), true);
          }
          return false;
        }
      });
      return false;
    }
  });

  $("#suggestPassword").on("submit", function() {
    var reqData = {
      id: 1,
      on: 'USER',
      'do': 'SUGGEST_EMAIL',
      data: {
        email: $('[name=email]', this).val(),
        password: $('[name=password]', this).val()
      }
    };
    $.ajax({
      type: "POST",
      url: lib.nodeapi,
      dataType: 'JSON',
      data: {
        msg: $.toJSON(reqData)
      },
      async: false,
      success: function(response) {
        nav.showPage('search');
        $('#RegUser').modal('hide');
        return false;
      }
    });
    return false;
  });

  $("#closeModalReg, #tosettings").on("click", function() {
    $('#RegUser').modal('hide');
    nav.showPage('search');
  });
  $("#topSearchForm .search-icon").on("click", function() {
    $("#topSearchForm").submit();
  });
  $("#topSearchForm").on("submit", function() {
    //nav.showPage('search?query=' + $("[name=query]", this).val());
    location.hash = '#search?query=' + $("[name=query]", this).val();
    return false;
  });
  $(document.body).on("submit", "#onmapSearchForm", function() {
    location.href = '#search?query=' + $("[name=query]", this).val();
    return false;
  });
  $(document.body).on("click", "#onmapSearchForm .search", function() {
    $("#onmapSearchForm").submit();
  });
  $(document.body).on("click", "#onmapSearchForm .express", function() {
    $("#onmapSearchForm").submit();
  });

  $("#shortRegForm [name=login]").on("keydown", function() {
    if ($(this).val().length > 2) {
      var reqData = {
        id: 1,
        on: 'USER',
        'do': 'CHECK_EMAIL',
        data: {
          email_like: $(this).val()
        }
      };
      $.ajax({
        type: "POST",
        url: lib.nodeapi,
        dataType: 'JSON',
        data: {
          msg: $.toJSON(reqData)
        },
        async: false,
        success: function(response) {
          if (response.data.emails.length) {
            $('.tryEmailList').show();
            $('.tryEmailList li').remove();
            for (var i = 0; i < response.data.emails.length; i++) {
              $('.tryEmailList').append('<li><span>' + response.data.emails[i] + '</span></li>');
            }
          } else {
            $('.tryEmailList').hide();
          }
        }
      });
    }
  });

  $(".tryEmailList").on("click", "li span", function() {
    $("#shortRegForm [name=login]").val($(this).text());
    $("#shortRegForm").submit();
  });

  $("#shortRegForm").on("submit", function() {
    lib.flag = $(this).attr('id');
    lib.flag2 = $('[name=login]', this).val();
    $(".tryEmailList").hide();
    if ($('#' + lib.flag + ' [name=do]').val() == 'REGISTER') {
      var reqData = {
        id: 1,
        on: 'USER',
        'do': $('#' + lib.flag + ' [name=do]').val(),
        data: {
          email: $("[name=login]", this).val(),
          ref_id: lib.refid
        }
      };
    } else {
      var reqData = {
        id: 1,
        on: 'USER',
        'do': $('#' + lib.flag + ' [name=do]').val(),
        data: {
          email: $("[name=login]", this).val(),
          password: $("[name=password]", this).val()
        }
      };
    }

    $.ajax({
      type: "POST",
      url: lib.nodeapi,
      dataType: 'JSON',
      data: {
        msg: $.toJSON(reqData)
      },
      async: false,
      success: function(response) {
        if (response.do =='REGISTER') {
          if (response.result == true) {
            //window.lib.showSuccess([response.data.message],$('#'+lib.flag),false);
            nav.userLogged = true;
            nav.drawRoof();
            $('#RegUser .state1').slideUp(200);
            $('#RegUser .state2').slideDown(200);
            $('#RegUser #newregemail').text(lib.flag2);
            $('#suggestPassword [name=email]').text(lib.flag2);
            if (lib.refid) {
              location.hash='#search';
            }
          } else {
            //значи авторизуемся - показываем поле пароль
            $('#' + lib.flag + ' [name=password]').slideDown('fast');
            $('#' + lib.flag + ' [name=do]').val('LOGIN');
          }
        } else if (response.do =='LOGIN') {
          if (response.result == true) {
            $('#RegUser').modal('hide');
            nav.userLogged = true;
            window.nav.showPage('profile');
          } else {            
            window.lib.showErrors([response.data.message], $('#' + lib.flag), false);
            $('#' + lib.flag + ' .infopanel').append('<button type="button" class="btn btn-info" id="resetPassword">Сбросить пароль</button>');
          }
        }
        return false;
      }
    });
    return false;
  });
  
  $(document.body).on("click", "#resetPassword", function() {
    var reqData = {
      "id": 1,
      "on": "USER",
      "do": "RESETPASSWORD",
      "data": {
        "email": $('#RegUser [name=login]').val()
      }
    }    
    $.ajax({
      type: "POST",
      url: lib.nodeapi,
      dataType: 'JSON',
      data: {
        msg: $.toJSON(reqData)
      },
      async: false,
      success: function(response) {
        if (response.result == true) {
          window.lib.showSuccess([response.data.message], $('#RegUser'), false);
        }
      }
    });    
  });
  
  $(document.body).on("submit", "#changePassword", function() {
    lib.flag = $(this).attr('id');
    if ($('[type=submit]', this).hasClass('disabled')) return false;
    $('[type=submit]', this).addClass('disabled');
    var error = [];
    var req = true;
    window.lib.hideErrors();
    $("[req='true']:visible", this).each(function(i) {
      $(this).parent().removeClass('has-error');
      if (!$(this).val().length) {
        $(this).parent().addClass('has-error');
        req = false;
      }
    });
    if (!req) error.push('Заполнены не все обязательные поля.');
    if (error.length) {
      window.lib.showErrors(error, this, true);
      $('[type=submit]', this).removeClass('disabled');
      return false;
    } else {
      var reqData = {
        "id": 1,
        "on": "USER",
        "do": "CHANGEPASSWORD",
        "data": {
          "password1": $('[name=password1]', this).val(),
          "password2": $('[name=password2]', this).val()
        }
      };
      $.ajax({
        type: "POST",
        url: lib.nodeapi,
        dataType: 'JSON',
        data: {
          msg: $.toJSON(reqData)
        },
        async: false,
        success: function(response) {
          if (response.result == true) {
            window.lib.showSuccess(['Изменения сохранены'], $('#' + lib.flag), true);
          } else {
            window.lib.showErrors([response.data.message], $('#' + lib.flag), true);
          }
          $('#'+lib.flag+' [type=submit]').removeClass('disabled');
          return false;
        }
      });
      return false;
    }
  });

  $("#logout").on("click", function() {
    nav.userLogged = false;
    /*var params = 'type=user&action=deauth';
    $.ajax({
       type: "POST",
       url: "/ansy/ajax.php",
       data: params,
       async: false,
       success: function(result){
          nav.showPage('');
       } 
    });  */
          
    var reqData = {
      id: 1,
      on: 'USER',
      'do': 'LOGOUT',
      data: {}
    };
    $.ajax({
      type: "POST",
      url: lib.nodeapi,
      dataType: 'JSON',
      data: {
        msg: $.toJSON(reqData)
      },
      async: false,
      success: function(response) {
        nav.showPage('');
      }
    });
    return false;
  });
  
  $('#RegUser').on('shown.bs.modal', function (e) {
    $('#RegUser .state1').show();
    $('#RegUser .state2').hide();
    $('#shortRegForm').hide();
    $('#shortRegForm .tryEmailList li').remove();
  })  

  $("#emeilRegChoise").on("click", function() {
    $("#shortRegForm").slideDown();
  });

  $(".el-icon-vkontakte").on("click", function() {
    $('#vkReg').submit();
    $('#RegUser').modal('hide');
  });

  $(".el-icon-facebook").on("click", function() {
    $('#fbReg').submit();
    $('#RegUser').modal('hide');
  });


  $(".profile-container .profile-container_photos a").on("click", function() {
    var photoImg = $(this).find("img").attr("big");
    mainPhotoImg = $(".profile-container .profile-container_mainphoto img").attr("src", photoImg);;
    return false;
  })
  
  $(document.body).on("click", ".btn-search", function() {
    var $this = $(this),
      $panel = $this.siblings(".field-search");
    $panel.is(":visible") ? $panel.hide() : $panel.show();
  })  

  $(document.body).on("click", ".btn-share", function() {
    var $this = $(this),
      $sharePanel = $(".profile-container_btns .btn-bookmarks_cnt");
    if ($this.hasClass("active")) {
      $this.removeClass("active");
      $sharePanel.hide();
    } else {
      $this.addClass("active");
      $sharePanel.show();
    }
    return false;
  })  

  $(".profile-container_info .profile_info_location").on("click", function() {
    var containerMap = $(this).siblings(".profile-container_map");
    containerMap.is(":visible") ? containerMap.hide() : containerMap.show();
  })

  $(".portrait-cnt_interest ul li a").on("click", function() {
    var $this = $(this),
      tag = $this.attr("data-tag");
    positionLink = $this.offset();
    $container = $this.parents('.portrait-cnt_interest'),
    $tag = $container.find(".float-tag");
    if (!$tag.length) {
      $container.prepend("<div data-toggle=\"" + tag + "\" class=\"float-tag\">Удалить</div>");
      $tag = $container.find(".float-tag");
    } else if ($tag.attr("data-toggle") == tag) {
      $tag.is(":visible") ? $tag.hide() : $tag.show();
    } else {
      $tag.attr("data-toggle", tag);
    }
    $tag.offset({
      top: positionLink.top - $this.outerHeight() - 12,
      left: positionLink.left + ($this.width() - $tag.outerWidth()) / 2
    });
  });

  $(".user-menu_settings_icon").on("click", function() {
    var $this = $(this),
      $popup = $("#userMenuSettings");
    if ($this.hasClass("active")) {
      $this.removeClass("active");
      $popup.hide();
    } else {
      $this.addClass("active");      
      $popup.position({
        left: $this.position().left + $this.outerWidth() - $popup.outerWidth()
      });
      $popup.show();
    }
    return false;
  });
  
  $("#userMenuSettings li a").on("click", function() {
      $("#userMenuSettings").hide();
      $(".user-menu_settings_icon").removeClass("active");
  });

  function showPopupForElem(elem, popup) {
    $(".user-menu_mail").not(elem).removeClass("active");
    $(".quick-message-list").hide();
    var $this = $(elem),
      $popup = $(popup);
    if ($this.hasClass("active")) {
      $this.removeClass("active");
      $popup.hide();
    } else {
      $this.addClass("active");
      $popup.show();
    }
    return false;
  }

  $("#myEmailMes1").on("click", function() {showPopupForElem(this, "#myEmailMessage1");});
  $("#myEmailMes2").on("click", function() {showPopupForElem(this, "#myEmailMessage2");});

  function destroyLessCache(pathToCss) {
    var host = window.location.host;
    var protocol = window.location.protocol;
    var keyPrefix = protocol + '//' + host + pathToCss;
    for (var key in window.localStorage) {
      if (key.indexOf(keyPrefix) === 0) {
        delete window.localStorage[key];
      }
    }
  }
  
  $(document.body).on("click", ".popup-location_reduce", onReducePopup);
  $(document.body).on("click", ".selector-city_target", onShowCityPanel);

  function onReducePopup() {
    var $this = $(this).parents(".popup-location");
    $this.hasClass("__reduce") ? $this.removeClass("__reduce") : $this.addClass("__reduce");
  }

  function onSearchCatalog() {
    var $this = $(this),
        $list = $this.siblings("ul"),
        query = $this.val().trim();
    $list.show();
    if (query.length) {
      $list.find("li").hide();
      $list.find("li:icontains(\"" + query + "\")").show();
    }
    else {
      $list.find("li").show();
    }
  }

  function onChooseCatalog() {
    var $this = $(this),
        $list = $this.parent();
    $list.siblings("input").val($this.text());
    $list.hide();
  }

  function onShowCityPanel() {
    var $this = $(this),
        $panel = $this.siblings(".selector-city_panel");
    $panel.is(":visible") ? $panel.hide() : $panel.show();
  }  
  //destroyLessCache("/shol/2/css/");
  //destroyLessCache("/css/");
});

jQuery.expr[':'].icontains = function(a, i, m) {
  return jQuery(a).text().toUpperCase()
      .indexOf(m[3].toUpperCase()) >= 0;
};